import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';
import 'package:date_format/date_format.dart';
import '../utils/StringCreate.dart';

class MailSender {
  static Future<bool> sendMessage(
      {required String targetMai, String title='肖肖饲养计划😀',required String info}) async {
    if (targetMai.isEmpty) {
      return false;
    }
    var username = '1125195347@qq.com';
    var password = 'fqhlzdytggsuhhjd';

    final smtpServer = qq(username, password);

    // Create our message.
    var timeNow = formatDate(
        DateTime.now(), [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]);
    final message = Message()
      ..from = Address(username, '肖肖饲养计划')
      ..recipients.add(targetMai)
      ..subject = title
      ..html = '<h1>来自系统的信息</h1>\n<p>$info</p><p>$timeNow</p>';
    try {
      final sendReport = await send(message, smtpServer);
      print('Message sent: ' + sendReport.toString());
      if (sendReport.toString().contains('success')) {
        return true;
      } else {
        return false;
      }
    } on MailerException catch (e) {
      print('Message not sent.$e');
      for (var p in e.problems) {
        print('Problem: ${p.code}: ${p.msg}');
      }
      return false;
    }
  }

  static Future<bool> sendVerifyNum(String targetMail) async {
    var vnum = createRandomVerifyNum(6);
    var message = 'Hey! 您的注册验证码为${vnum}，有效时间为5分钟';
    var if_send = await sendMessage(targetMai: targetMail, info: message);
    if (!if_send) {
      return false;
    }
    return true;
  }
}
